﻿using Furion;
using Microsoft.AspNetCore.Builder;
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SqlSugar;
using SqlSugar_Bugs.Entities;
using System.Diagnostics;

namespace SqlSugar_Bugs
{
    internal class Program
    {
        public const string BASE_DB_NAME = "BaseDatabase.db";
        public const string TASK_DB_NAME = "TaskData.db";

        static void Main(string[] args)
        {
            var appDataDir = Path.Combine(AppContext.BaseDirectory, "App_Data");
            if (!Directory.Exists(appDataDir))
            {
                Directory.CreateDirectory(appDataDir);
            }

            const DbType dbType = DbType.Sqlite;

            var baseDbFile = Path.Combine(appDataDir, BASE_DB_NAME);
            var baseConnectionConfig = CreateConnectionConfig(dbType, BASE_DB_NAME, baseDbFile);

            var taskDataDbFile = Path.Combine(appDataDir, TASK_DB_NAME);
            var taskDataConnectionConfig = CreateConnectionConfig(dbType, TASK_DB_NAME, taskDataDbFile);

            var db = new SqlSugarScope([baseConnectionConfig, taskDataConnectionConfig]);

            // 创建第一个库
            var db1 = db.AsTenant().GetConnectionScope(BASE_DB_NAME);
            db1.DbMaintenance.CreateDatabase();
            db1.CodeFirst.SetStringDefaultLength(255).InitTables(typeof(UserEntity));

            // 创建第二个库
            var db2 = db.AsTenant().GetConnectionScope(TASK_DB_NAME);
            db2.DbMaintenance.CreateDatabase();
            db2.CodeFirst.SetStringDefaultLength(255).InitTables(typeof(ReportRecordEntity));

            var builder = Host.CreateDefaultBuilder(args).Inject();
            builder.ConfigureServices(services =>
            {
                services.AddSingleton<ISqlSugarClient>(serviceProvider => db);
                services.AddSingleton<ReportRecordService>();
                services.AddHostedService<WorkingService>();
            });

            var app = builder.Build();
            app.Run();
        }

        private static ConnectionConfig CreateConnectionConfig(DbType dbType, string dbName, string dbFile)
        {
            var connectionStringBuilder = new SqliteConnectionStringBuilder()
            {
                Mode = SqliteOpenMode.ReadWriteCreate,
                Cache = SqliteCacheMode.Shared,
                DataSource = dbFile,
                Pooling = true
            };

            return new ConnectionConfig()
            {
                ConfigId = dbName,
                ConnectionString = connectionStringBuilder.ToString(),
                DbType = dbType,
                InitKeyType = InitKeyType.Attribute,
                IsAutoCloseConnection = true,
                ConfigureExternalServices = new ConfigureExternalServices()
                {
                    EntityService = (x, p) => // ToUnderLine驼峰转下划线方法
                    {
                        p.DbColumnName = UtilMethods.ToUnderLine(p.DbColumnName);
                    },
                },
                AopEvents = new AopEvents
                {
#if DEBUG
                    // 多库状态下每个库必须单独绑定打印事件，否则只会打印第一个库的sql日志
                    OnLogExecuting = (sql, pars) =>
                    {
                        string sqlStr = UtilMethods.GetSqlString(dbType, sql, pars);
                        Debug.WriteLine(sqlStr);
                    },
#endif
                    OnError = (ex) =>
                    {
                        //var logger = _serviceProvider.GetService<ILogger<Program>>();
                        //logger.LogError(UtilMethods.GetSqlString(dbType, ex.Sql, (SugarParameter[])ex.Parametres));
                    }
                }
            };
        }

    }
}
